using System;
using System.ServiceModel.DomainServices.Client;
using MedLink2011.Web.Services;

namespace MedLink2011.Core
{
    public class PerformAsyncQueryBase : ViewModelBase
    {
        protected void PerformAsyncQuery<T>(MedLink2011Context context4Query, EntityQuery<T> qry, EventHandler<MedLink2011.Core.EntityResultsArgs<T>> evt) where T : Entity
        {

            context4Query.Load<T>(qry, LoadBehavior.RefreshCurrent, r =>
                                                                     {
                                                                         if (evt != null)
                                                                         {
                                                                             try
                                                                             {
                                                                                 if (r.HasError)
                                                                                 {
                                                                                     evt(this, new MedLink2011.Core.EntityResultsArgs<T>(r.Error));
                                                                                     r.MarkErrorAsHandled();
                                                                                 }
                                                                                 else
                                                                                 {
                                                                                     evt(this, new MedLink2011.Core.EntityResultsArgs<T>(r.Entities));
                                                                                 }
                                                                             }
                                                                             catch (Exception ex)
                                                                             {
                                                                                 evt(this, new MedLink2011.Core.EntityResultsArgs<T>(ex));
                                                                             }
                                                                         }
                                                                     }, null);

        }
    }
}